package org.mclll.xwangplugin.town.command.executor;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.mclll.xwangplugin.town.database.domain.TownDO;
import org.mclll.xwangplugin.town.database.domain.TownPlayerDO;
import org.mclll.xwangplugin.town.database.mapper.manage.TownManage;
import org.mclll.xwangplugin.town.database.mapper.manage.TownPlayerManage;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;

import static org.mclll.xwangplugin.town.config.TownContext.*;
import static org.mclll.xwangplugin.util.PlayerTools.getPeopleInfo;

/**
 * @author: geduo
 * @date: 2023/9/23 19:29
 */
public class TownInfoExecutor {

    public static void townInfo(CommandSender sender, String[] args) {
        // /poitown townInfo <城镇uuid>
        if (args.length != 2) {
            return;
        }
        String uuid = args[1];
        TownDO selectParam = new TownDO();
        selectParam.setUuid(uuid);
        List<TownDO> townList = TownManage.selectList(selectParam);
        if (townList.isEmpty()) {
            sender.sendMessage(TOWN_NOT_FOUND);
            return;
        }
        TownDO town = townList.get(0);
        TownPlayerDO playerSelectParam = new TownPlayerDO();
        playerSelectParam.setTownUuid(town.getUuid());
        List<TownPlayerDO> townPlayerList = TownPlayerManage.selectList(playerSelectParam);
        Collection<? extends Player> onlinePlayers = sender.getServer().getOnlinePlayers();
        boolean playerListEmpty = townPlayerList.isEmpty();
        TextComponent.Builder message = Component.text().append(Component.text(String.format(TOWN_DETAIL_TITLE, town.getName())));
        if (!playerListEmpty) {
            townPlayerList.sort(Comparator.comparing(TownPlayerDO::getIdentity));
            message.append(getPeopleInfo(townPlayerList, onlinePlayers));
        }
        sender.sendMessage(message.appendNewline()
                .append(Component.text(String.format(TOWN_DETAIL_LINE_3, town.getTownLevel().name)))
                .appendNewline()
                .append(Component.text(String.format(TOWN_DETAIL_LINE_4, town.getTownParty().name)))
                .appendNewline()
                .append(Component.text(String.format(TOWN_DETAIL_LINE_5, town.getMonthTax(), town.getTownLevel().totalTax())))
                .appendNewline()
                .append(Component.text(String.format(TOWN_DETAIL_LINE_6, town.getTotalTax())))
                .build()
        );
    }
}
